import { Config, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BroadcastAudioEntity } from '../entity/audio';
import { UserAudioSettingEntity } from '../../user/entity/setting';
const fs = require("fs")
/**
 * 背景音频
 */
@Provide()
export class BroadcastAudioService extends BaseService {

  @InjectEntityModel(BroadcastAudioEntity)
  broadcastAudioEntity: Repository<BroadcastAudioEntity>;

  @InjectEntityModel(UserAudioSettingEntity)
  UserAudioSettingEntity: Repository<UserAudioSettingEntity>;

  @Config('module.broadcast')
  broConfig;


  /**
     * 更新
     * @param param
     */
  async update(param) {
    if(param.isDefault==1){
       let is_default=await this.broadcastAudioEntity.findOneBy({isDefault:1})
       if(is_default){
        await this.broadcastAudioEntity.save({...is_default,isDefault:0})
       }
    }
    await super.update(param);
  }
  /**
  * 删除
  * @param ids
  */
  async delete(ids) {
    let idArr;
    if (ids instanceof Array) {
      idArr = ids;
    } else {
      idArr = ids.split(',');
    }
    for (const id of idArr) {
      // 删除文件夹下的文件
      let file = `${this.broConfig.savePath}/modules/broadcast/files/background/${id}.mp3`
      if (fs.existsSync(file)) {
        fs.unlink(file, (err) => { })
      }
      // 默认背景音频id为当前id的用户,统一置空
      await this.nativeQuery(
        `UPDATE user_audio_setting SET audioId = NULL WHERE audioId = ${id}`
      );
      await this.broadcastAudioEntity.delete({ id });
    }
  }
}
